package com.zhang.third.day04;

import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.util.Collector;

import java.util.Random;

/**
 * @title: 传感器连续温度1s上升检测
 * @author: zhang
 * @date: 2022/4/7 11:08
 */
public class Example2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new SensorSource())
                .keyBy(r -> r.sensorId)
                .process(new KeyedProcessFunction<String, SensorReading, String>() {
                    private ValueState<Double> lastTemp; // 保存上一次温度值
                    private ValueState<Long> timerTs; // 保存定时器时间戳

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        lastTemp = getRuntimeContext().getState(
                                new ValueStateDescriptor<Double>(
                                        "last-temp", Types.DOUBLE
                                )
                        );
                        timerTs = getRuntimeContext().getState(
                                new ValueStateDescriptor<Long>(
                                        "timer-ts", Types.LONG
                                )
                        );
                    }

                    @Override
                    public void processElement(SensorReading value, KeyedProcessFunction<String, SensorReading, String>.Context ctx, Collector<String> out) throws Exception {
                        Double preTemp = lastTemp.value(); // 取出上一次温度
                        lastTemp.update(value.temperature); // 保存当前温度
                        // 从第二条数据开始处理，也就是要求必须有上一次温度值
                        if (preTemp != null) {
                            // 温度上升并且没有注册定时器
                            if (value.temperature > preTemp && timerTs.value() == null) {
                                // 注册报警定时器
                                long oneSecLater = ctx.timerService().currentProcessingTime() + 1000L;
                                ctx.timerService().registerProcessingTimeTimer(oneSecLater);
                                timerTs.update(oneSecLater);

                            } // 温度下降并且存在报警定时器
                            else if (value.temperature < preTemp && timerTs.value() != null) {
                                // 删除定时器
                                ctx.timerService().deleteProcessingTimeTimer(timerTs.value());
                                timerTs.clear();
                            }
                        }
                    }

                    @Override
                    public void onTimer(long timestamp, KeyedProcessFunction<String, SensorReading, String>.OnTimerContext ctx, Collector<String> out) throws Exception {
                        out.collect("传感器：" + ctx.getCurrentKey() + "连续1s温度上升，报警！！！");
                        timerTs.clear();
                    }
                })
                .print();

        env.execute();
    }

    // 自定义数据源
    public static class SensorSource implements SourceFunction<SensorReading> {
        private boolean running = true;
        private Random random = new Random();

        @Override
        public void run(SourceContext<SensorReading> ctx) throws Exception {
            while (running) {
                for (int i = 1; i < 4; i++) {
                    ctx.collect(new SensorReading(
                            "sensor_" + i,
                            random.nextGaussian()
                    ));
                }
                Thread.sleep(300L);
            }
        }

        @Override
        public void cancel() {
            running = false;
        }
    }

    // POJO CLASS
    public static class SensorReading {
        public String sensorId;
        public Double temperature;

        public SensorReading() {
        }

        public SensorReading(String sensorId, Double temperature) {
            this.sensorId = sensorId;
            this.temperature = temperature;
        }
    }
}
